import connect from "@/utils/mongodb";
import User from "@/model/User";
import { NextResponse } from "next/server";

export const POST = async (request) => {
  try {
    const { name } = await request.json();
    if (!name) {
      return NextResponse.json(
        { message: "请输入用户名", isExisted: false },
        { status: 400 }
      );
    }

    await connect();
    // 检查数据库中是否存在相同姓名的用户
    const existingUser = await User.findOne({ name });

    return NextResponse.json({
      isExisted: !!existingUser, // 存在则返回 true，否则 false
      message: existingUser ? "用户名已被使用" : "用户名可用"
    });
  } catch (error) {
    console.error("检查用户名失败:", error);
    return NextResponse.json(
      { message: "检查用户名失败", isExisted: false },
      { status: 500 }
    );
  }
};